package cn.edu.wfit.controller;

import cn.edu.wfit.entity.JsonResult;
import cn.edu.wfit.entity.Students;
import cn.edu.wfit.service.IRoleService;
import cn.edu.wfit.service.IStudentsService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/Students")
public class StudentsController {
    @Autowired
    private IStudentsService service;
    @Autowired
    private IRoleService roleService;
    @GetMapping
    @PreAuthorize("hasRole('操作员')")
    public JsonResult getAll(Students students){
        LambdaQueryWrapper<Students> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(students.getName()),Students::getName,students.getName());
        boolean hasText=StringUtils.hasText(students.getName());
        boolean hasText1=StringUtils.hasText(String.valueOf(students.getId()));
        queryWrapper.like(hasText,Students::getName,students.getName());
        queryWrapper.like(hasText1,Students::getId,students.getId());
        List<Students> list=service.list(queryWrapper);
        return JsonResult.ok(list);

    }
    @GetMapping ("/{id}")
    @PreAuthorize("hasRole('操作员')")
    public JsonResult getById(@PathVariable long id){

       Students save = service.getById(id);

        return JsonResult.ok(save);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('管理员')")
    public JsonResult del(@PathVariable Long id){

        boolean b = service.removeById(id);
        if(b){
            return JsonResult.ok("删除"+id+"成功");
        }
        return JsonResult.failure(500,"删" +
                "除"+id+"成功");
    }
    @PutMapping
    @PreAuthorize("hasRole('管理员')")
    public JsonResult edit(@RequestBody Students students){
        if(students.getId()==null){
            return JsonResult.failure(400,"id不能为空");
        }
        boolean save = service.updateById(students);
        if(save){
            return JsonResult.ok("修改成功");
        }
        return JsonResult.failure(500,"修改失败");
    }
    @PostMapping
    @PreAuthorize("hasRole('管理员')")
    public JsonResult add(@RequestBody Students students){
        boolean save = service.save(students);
        if(save){
            return JsonResult.ok("保存成功");
        }
        return JsonResult.failure(500,"保存失败");
    }

}
